# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import auth
from django.contrib.auth.models import User
from django.db.models import F

import apps, datetime
from apps.comment.models import Comment
from apps.comment.forms import CommentForm

from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.utils import simplejson as json
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import Paginator, InvalidPage, EmptyPage


@login_required
def create(request, contype, conid):
    if request.method == 'POST' and contype in["activity", "post", ]: 
        conname = getattr(apps, contype)
        conModel = getattr(conname.models, contype.capitalize())
        try:
            coninstance = conModel.objects.get(pk=conid) 
        except ObjectDoesNotExist:
            raise Http404('评论对象已删除')
        comment = Comment(author = request.user, master = coninstance )
        form = CommentForm(request.POST, instance=comment)
        if form.is_valid():
            comment = form.save()
            coninstance.commentcount = F('commentcount') +1
            coninstance.updatedtime = datetime.datetime.now()
            coninstance.save()            
            return HttpResponseRedirect('/%s/%s/?page=999#comment' % (contype, conid) )
        else:
            if form["content"].errors :
                form["content"].errors[0] = u"*必填，不超过一千字"
            return render_to_response('comment/create.html', {'form': form}
                ,context_instance=RequestContext(request) )
    form = CommentForm()
    return render_to_response('comment/create.html', {'form': form}
                    ,context_instance=RequestContext(request) )


@login_required
def delete(request, id):
    if request.user != Comment.objects.get(pk=id).author:
        raise Http404('不具有该权限，或请先登录')
    #if 'makesure' in request.GET and request.GET['makesure']:
    comment = Comment.objects.get(pk=int(id))
    coninstance = comment.master
    coninstance.commentcount = F('commentcount') -1
    coninstance.save() 
    
    comment.delete()
    contype = ContentType.objects.get_for_model(coninstance)
    return HttpResponse(json.dumps({"state":"ok"}), mimetype="application/json")
    #return HttpResponseRedirect("/" + contype.model + "/" + str(coninstance.id ) )
